// pages/checkIn/checkIn.js
const app = getApp();
var util = require('../../utils/util.js');
import throttle from '../../utils/throttle.js';
const date = new Date();

Page({
    /**
     * 页面的初始数据
     */
    data: {
        ipxBottom: 0,
        // 打卡次数
        checknum: '',
        titleDescription: '',
        sceneImageArr: [], //上传照片
        // 图片描述
        description: [],
        // 当前描述索引
        currentDesIndex: 0,
        // 当前图片索引
        currentPicIndex: 0,
        // 打卡数
        checkRadioItems: [
            {
                name: '工作打卡',
                value: '01',
                checked: true,
            },
            {
                name: '旅行路过',
                value: '00',
                checked: false,
            },
        ],
        selectValue: '01',
        // 图片描述弹窗
        showDescBox: false,
        descBoxBottom: 0, //回答弹窗键盘高度
        itemDescription: '', //弹窗输入内容
        firstparty: '', //服务客户，逗号拼接的字符串
        defaultFirstparty: '', //默认服务客户
        isSubmiting: false, //是否正在提交
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        if (app.globalData.isIpx) {
            this.setData({
                ipxBottom: 34,
            });
        }
        if (options.firstparty) {
            this.setData({
                firstparty: options.firstparty,
                defaultFirstparty: options.firstparty,
            });
        }
        this.setData({});
        this.getminePageNum();
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {},
    titleDes(e) {
        this.setData({
            titleDescription: e.detail.value,
        });
        app.numLimitTip(e.detail.value.length, 200);
    },
    //旅游、打卡选项
    radioChange(e) {
        this.setData({
            selectValue: e.detail.value,
        });
    },

    // 添加图片
    addImg(e) {
        const _that = this;
        wx.chooseImage({
            count: 9 - _that.data.sceneImageArr.length,
            success(res) {
                let imgLen =
                    _that.data.sceneImageArr.length + res.tempFilePaths.length;
                if (imgLen > 9) {
                    wx.showModal({
                        content: '最多上传9张图片，请重新上传',
                        showCancel: false,
                    });
                    return;
                } else {
                    wx.showLoading({
                        title: '图片上传中',
                        mask: true,
                    });
                    const imgUploadResults = [];
                    let index = _that.data.sceneImageArr.length;
                    for (let i = 0; i < res.tempFilePaths.length; i++) {
                        let imgUploadResult = app
                            .imgUpload(res.tempFilePaths[i])
                            .then((res) => {
                                let num = i + index;
                                _that.data.sceneImageArr[num] = res;
                                _that.setData({
                                    sceneImageArr: _that.data.sceneImageArr,
                                });
                                console.log(_that.data.sceneImageArr);
                            });
                        imgUploadResults.push(imgUploadResult);
                    }
                    Promise.all(imgUploadResults).then((values) => {
                        wx.hideLoading();
                    });
                }
            },
        });
    },
    // 删除图片
    deleteImg(e) {
        let index = e.currentTarget.dataset.index;
        this.data.sceneImageArr.splice(index, 1);
        // 如果该图片有图片描述也需要删除
        if (this.data.description[index]) {
            this.data.description.splice(index, 1);
        }
        this.setData({
            sceneImageArr: this.data.sceneImageArr,
            description: this.data.description,
        });
    },
    // 预览图片
    previewImgDes(e) {
        let index = e.currentTarget.dataset.index;
        this.setData(
            {
                currentPicIndex: index,
            },
            () => {
                wx.navigateTo({
                    //hideBottom隐藏图片预览的删除按钮
                    url: `./imgPreview/imgPreview?hideBottom=${true}`,
                });
            }
        );
    },
    // 显示图片描述谁弹窗
    showDescBox(e) {
        console.log(e.currentTarget.dataset.index);
        this.setData(
            {
                showDescBox: true,
                currentDesIndex: e.currentTarget.dataset.index,
                itemDescription:
                    this.data.description[e.currentTarget.dataset.index],
            },
            () => {
                wx.onKeyboardHeightChange((res) => {
                    this.setData({
                        descBoxBottom: res.height,
                    });
                });
            }
        );
    },
    itemDescription(e) {
        this.setData({
            itemDescription: e.detail.value,
        });
        app.numLimitTip(e.detail.value.length, 200);
    },
    submitDesc(e) {
        let arr = this.data.description;
        arr[this.data.currentDesIndex] = this.data.itemDescription;
        this.setData({
            description: arr,
            showDescBox: false,
        });
    },
    hideCover(e) {
        this.setData({
            showDescBox: false,
            itemDescription: '',
        });
    },
    stopcovermove(e) {
        return;
    },
    // 提交
    submit: throttle(
        function (e) {
            let _that = this;
            if (app.visitorPublish()) return; //游客发布限制
            if (
                _that.data.sceneImageArr.length &&
                _that.data.selectValue &&
                !_that.data.isSubmiting
            ) {
                //判断灰色图标
                let time = util.formatDate(new Date());
                let date = util.getDates(1, time);
                let dates = new Date();
                let dateHours =
                    dates.getHours() < 10
                        ? '0' + dates.getHours()
                        : dates.getHours(); //获取小时
                let dateMinutes =
                    dates.getMinutes() < 10
                        ? '0' + dates.getMinutes()
                        : dates.getMinutes(); //获取分钟
                let dateSeconds =
                    dates.getSeconds() < 10
                        ? '0' + dates.getSeconds()
                        : dates.getSeconds();
                let descArr = [];
                for (let i = 0; i < _that.data.sceneImageArr.length; i++) {
                    descArr.push(_that.data.description[i] || '');
                }
                // 正在提交
                _that.setData({
                    isSubmiting: true,
                });
                wx.request({
                    url:
                        app.globalData.rootPath +
                        `cjMap/createCheckin?authId=${app.globalData.authId}`,
                    method: 'POST',
                    header: {
                        'content-type': 'application/json', // 默认值
                    },
                    data: {
                        checkintime:
                            date[0].time +
                            ' ' +
                            dateHours +
                            ':' +
                            dateMinutes +
                            ':' +
                            dateSeconds,
                        type: _that.data.selectValue,
                        mode: '00',
                        delflg: '00',
                        cityname: app.globalData.addressBack,
                        picdescriptions: descArr,
                        description: _that.data.titleDescription,
                        picurls: _that.data.sceneImageArr,
                        country: app.globalData.countryBack,
                        firstparty:
                            _that.data.selectValue === '01'
                                ? _that.data.firstparty
                                : '',
                        province: app.globalData.province,
                        district: app.globalData.district,
                        lat: app.globalData.locationLat,
                        lng: app.globalData.locationLng,
                    },
                    success: function (res) {
                        if (res.data.status != 1) {
                            wx.showToast({
                                title: '打卡成功',
                                icon: 'success',
                                duration: 1500,
                            });
                            _that.getminePageNum();
                            setTimeout(function () {
                                wx.redirectTo({
                                    url: `../minePage/checkNumber/checkNumber?checkinnum=${_that.data.checknum}`,
                                });
                                _that.setData({
                                    isSubmiting: false,
                                });
                            }, 1500);
                        } else {
                            wx.showToast({
                                title: res.data.errmsg,
                                icon: 'none',
                                duration: 1500,
                            });
                            setTimeout(function () {
                                wx.navigateBack({
                                    delta: 1, // 返回上一级页面。
                                });
                                _that.setData({
                                    isSubmiting: false,
                                });
                            }, 1500);
                        }
                    },
                });
            }
        },
        5000,
        {
            trailing: false,
        }
    ),
    // 打卡数获取
    getminePageNum() {
        let _that = this;
        wx.request({
            url: app.globalData.rootPath + `cjMap/personalPageNum`,
            method: 'GET',
            header: {
                'content-type': 'application/x-www-form-urlencoded',
            },
            data: {
                authId: app.globalData.authId,
            },
            success: function (res) {
                _that.setData({
                    checknum: res.data.data.checkinnum,
                });
            },
        });
    },

    changeNav: throttle(
        (e) => {
            let { nav } = e.currentTarget.dataset;
            console.log(nav);
            wx.navigateTo({
                url: `${nav}`,
            });
        },
        200,
        {
            trailing: false,
        }
    ),

    /**
     * 删除选中的服务客户
     */
    deleteCustomer() {
        this.setData({
            firstparty: '',
        });
    },
});
